//获取基地址
axios.defaults.baseURL = "http://ajax-base-api-t.itheima.net";

//获取元素
const tb = document.querySelector('#tb')
const form = document.querySelector('#bookForm')

const rederbox = async (params) => {
  const { data: { data: res } } = await axios.get('/api/getbooks', { params })
  const html = res.map(item => {
    return `
        <tr>
          <td>${item.id}</td>
          <td>${item.bookname}</td>
          <td>${item.author}</td>
          <td>${item.publisher}</td>
          <td><a href="#" data-id = ${item.id}>删除</a></td>
          </tr>
          `
  }).join('')
        tb.innerHTML = html
  }
rederbox()

//添加
form.addEventListener('click', async function (e) {
  e.preventDefault()
  if (e.target.dataset.name === 'tian') {
    const data = serialize(this, { hash: true })
  const {data : res} =  await axios({
    url: '/api/addbook',
    method: 'POST',
    data
  }) 
    alert(res.msg)
    if (!(res.status === 201)) return  console.log(res.status);
    this.reset()
    rederbox()
 }
})

//删除
tb.addEventListener('click',async function (e) {
  if (e.target.tagName === 'A') {
    const id = e.target.dataset.id
  const {data : res} =   await axios({
      url: '/api/delbook',
      params : {id}
    })
      alert(res.msg)
      rederbox()
  }
})

//筛选
form.addEventListener('click', function (e) {
  if (e.target.dataset.name === 'sai') {
    const data = serialize(this, { hash: true })
    rederbox(data)
  }
})
